package com.inctech.filter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.inctech.model.Statistic;
import com.inctech.utils.AddressUtils;

public class MyFilter implements Filter{

	private FilterConfig filterConfig;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		ServletContext context = filterConfig.getServletContext();
		Map<String, Integer> ipMap = (Map<String, Integer>) context.getAttribute("ipMap");
		List<Statistic> ipList = (List<Statistic>) context.getAttribute("ipList");
		String ip = request.getRemoteAddr();
		if(ipMap.containsKey(ip)){
			Integer count = ipMap.get(ip);
			ipMap.put(ip,count+1);
		}else{
			ipMap.put(ip,1);
		}
		
		AddressUtils addressUtils = new AddressUtils();
		
		for (Map.Entry<String, Integer> entry : ipMap.entrySet()) {
			   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
			   String ip_ = entry.getKey();
			   Integer count_ = entry.getValue();
			   String address_ = "";
			   address_ = addressUtils.getAddresses("ip=" + ip_, "utf-8");
			   Statistic statistic = new Statistic(ip_, address_, count_);
			   ipList.add(statistic);
		}
		
		context.setAttribute("ipList", ipList);
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
